package com.geek.service;

import com.geek.dao.BlogRepository;
import com.geek.po.Blog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogRepository blogRepository;

    @Override
    public Blog getBlog(Long id) {
        boolean exist = blogRepository.existsById(id);
        if (!exist) {
            return null;
        }
        return blogRepository.getById(id);
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        Page<Blog> all = blogRepository.findAll(pageable);

        // 处理博客...问题
        List<Blog> content = all.getContent();
        for (Blog blog : content) {
            String title = blog.getTitle();
            if (title.length() > 20) {
                title = title.substring(0, 20) + "......";
            }
            String description = blog.getDescription();
            if (description.length() > 40) {
                description = description.substring(0, 40) + "......";
            }
            blog.setTitle(title);
            blog.setDescription(description);
        }

        return all;
    }

    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "views");
        Pageable pageable = PageRequest.of(0, size, sort);
        return blogRepository.findTop(pageable);
    }

    @Override
    public Long countBlog() {
        return blogRepository.count();
    }

    @Transactional
    @Override
    public Blog saveBlog(Blog blog) {
        return blogRepository.save(blog);
    }

}
